<?php

namespace app\admin\controller;

use app\admin\controller\CommonController;
use app\admin\model\Admin;
use think\Db;
use think\Validate;
use app\util\File;
use think\Request;
use app\admin\model\Sellrole;
use app\admin\model\Adminrole;
use app\admin\model\Store;

class AdminController extends CommonController {
    /*
     * 管理员列表 
     * author xfwed
     * date 2019.08.31
     */

    public function AdminList() {
        $admin = new Admin();
        $status = input('param.status');
        $type = input('param.type'); //类型 0全部 1后台管理员 2代理 

        $perPage = input('param.perPage');
        $page = input('param.page');
        
        if($type){
            $where['type'] = $type;
        }
        
        $status = isset($status) ? $status : 1;
        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page)?$page:1;
        $where = isset($where) ? $where : [];
        $adminList = Admin::order("id asc")
                ->where($where)
                ->where('status', '=', $status)
                ->field('id,admin_name,admin_note,photo,role,last_time,login_ip,status,jobnum,type')
                ->paginate($perPage);
        return $this->ajaxReturn(0, '查询成功', $adminList);
    }

    /*
     * 添加管理员
     * author xfwed
     * date 2019.08.31
     */

    public function AddAdmin() {
        $rule = [
            'admin_name' => 'require',
            'admin_note' => 'require',
            'type' => 'require',
            'admin_pwd' => 'require|min:6',
        ];
        $msg = [
            'admin_name.require' => '账号必须',
            'admin_note.require' => '名称必须',
            'type.require' => '类型必须',
            'admin_pwd.require' => '密码必须',
            'admin_pwd.min' => '密码最少6位',
        ];
        $all = input('post.');
        $validate = new Validate($rule, $msg);

        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $adminname = Admin::where("admin_name='" . $all['admin_name'] . "'")->find();
        if ($adminname) {
            return $this->ajaxReturn('3', '该账号已经存在', null);
        }

        $data['admin_name'] = $all['admin_name'];
        $data['admin_note'] = $all['admin_note'];
        $data['admin_pwd'] = md5($all['admin_pwd']);
        $data['type'] = $all['type'];
        $data['status'] = 1;
        $data['last_time'] = date('Y-m-d H:i:s');
        $data['login_ip'] = Request::instance()->ip(); //登陆ip
        $data['photo'] = $all['photo'];
        $data['jobnum'] = input('param.jobnum');
        $data['add_time'] = date('Y-m-d H:i:s');
        $add = Db::name('admin')->insert($data);
        if ($add) {
            return $this->ajaxReturn(0, '添加成功', null);
        } else {
            return $this->ajaxReturn(3, '添加失败', null);
        }
    }

    /*
     * 管理员信息  编辑前调用
     * author xfwed
     * date 2019.09.07
     */

    public function AdminInfo() {
        $id = input('param.id');
        $adminFied = Admin::where('id=' . $id)->find();
        return $this->ajaxReturn(0, '查询成功', $adminFied);
    }

    /*
     * 编辑管理员
     * author xfwed
     * date 2019.09.07 
     */

    public function AdminEdit() {
        $id = input('param.id');
        $adminFied = Admin::where('id=' . $id)->find();
        $rule = [
            'admin_name' => 'require',
            'admin_note' => 'require',
            'type' => 'require',
            'admin_pwd' => 'require|min:6',
        ];
        $msg = [
            'admin_name.require' => '账号必须',
            'admin_note.require' => '名称必须',
            'type.require' => '类型必须',
            'admin_pwd.require' => '密码必须',
            'admin_pwd.min' => '密码最少6位',
        ];
        $all = input('post.');
        $validate = new Validate($rule, $msg);

        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }


        $data['admin_name'] = $all['admin_name'];
        $data['admin_note'] = $all['admin_note'];
        $data['admin_pwd'] = md5($all['admin_pwd']);
        $data['type'] = $all['type'];
        $data['status'] = 1;
        $data['last_time'] = date('Y-m-d H:i:s');
        $data['login_ip'] = Request::instance()->ip(); //登陆ip
        $data['photo'] = $all['photo'];
        $data['jobnum'] = input('param.jobnum');
        $save = Admin::where("id=" . $id)->update($data);
        if ($save) {
            return $this->ajaxReturn(0, '修改成功', null);
        } else {
            return $this->ajaxReturn(3, '修改失败', null);
        }
    }

    /*
     * 改变状态
     * author xfwed
     * date 2019.09.07 
     */

    public function AdminStatus() {
        $id = input('param.id');
        $status = input('param.status');
        $data['status'] = $status;
        $save = Admin::where("id=" . $id)->update($data);
        if ($save) {
            return $this->ajaxReturn(0, '修改成功', null);
        } else {
            return $this->ajaxReturn(3, '修改失败', null);
        }
    }

    /*
     * 权限管理
     * author xfwed
     * date 2019.09.07
     */

    public function role() {
        $id = input('param.id');
        $adminFied = Admin::where('id=' . $id)->find();
        $role = $adminFied['role'];
        $roledata = Adminrole::where('pid', '=', 0)
                ->field('id,pid,name')
                ->order('sort asc')
                ->select();
        for ($i = 0; $i < count($roledata); $i++) {
            if (in_array($roledata[$i]['id'], explode(",", $role))) {
                $roledata[$i]['state'] = 1;
            } else {
                $roledata[$i]['state'] = 2;
            }
            $pdata = Adminrole::where('pid', '=', $roledata[$i]['id'])
                    ->field('id,pid,name')
                    ->order('sort asc')
                    ->select();

            for ($j = 0; $j < count($pdata); $j++) {
                if (in_array($pdata[$j]['id'], explode(",", $role))) {
                    $pdata[$j]['state'] = 1;
                } else {
                    $pdata[$j]['state'] = 2;
                }
            }
            $roledata[$i]['pdata'] = $pdata;
        }

        //$returndata = json_encode($returndata);
        return $this->ajaxReturn(0, '查询成功', $roledata);
    }

    /*
     * 修改权限
     * author xfwed
     * date 2019.09.07
     */

    public function saveRole() {
        $id = input('param.id');

        $role = input('post.role');
        $data['role'] = $role;
        $save = Admin::where("id=" . $id)->update($data);
        if ($save) {
            return $this->ajaxReturn(0, '修改成功,重新登录以后生效', null);
        } else {
            return $this->ajaxReturn(3, '修改失败', null);
        }
    }

    /*
     * 修改密码
     * author xfwed
     * date 2019.09.07
     */

    public function savepwd() {
        $id = input('param.id');
        $newpwd = input('param.newpwd');
        $oldpwd = input('param.oldpwd');
        $row = Admin::where("id=" . $id)->where('type', '=', 1)->find();
        if (empty($row)) {
            return $this->ajaxReturn(3, '没有发现该用户', null);
        }
        if (md5($oldpwd) != $row['admin_pwd']) {
            return $this->ajaxReturn(3, '旧密码输入错误', null);
        }
        $save = Admin::where("id=" . $id)->update(['admin_pwd' => md5($newpwd)]);

        if ($save) {
            return $this->ajaxReturn(4, '修改成功,请重新登录', null);
        } else {
            return $this->ajaxReturn(3, '修改失败', null);
        }
    }

    /*
     * 代理绑定店铺
     * author xfwed
     * date 2020-08-17
     */

    public function agencyBindStore() {
        $id = input('param.id');//代理id
        $store_ids = input('param.store_ids');
        Db::startTrans();
        $row = Store::where('agency_id',$id)->find();
        if($row){
            $saveold = Store::where('agency_id',$id)->update(['agency_id'=>0]);
        }  else {
            $saveold = TRUE;
        }
        $savenew = Store::where('id','in',$store_ids)->update(['agency_id' => $id]);
        if($saveold && $savenew){
           Db::commit();
           return $this->ajaxReturn(0, '绑定成功', null);
        }  else {
           Db::rollback(); 
           return $this->ajaxReturn(3, '绑定失败', null);
        }
        
    }

}
